package xuan.mall.system.infrastructure.security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

/**
 * @author: rongxuanzhou
 * @create: 2025/6/1
 * @Description:
 */
@Configuration
public class CorsConfig {

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        //应替换为实际的前端地址
        config.setAllowedOrigins(Arrays.asList(
                "http://localhost:5173"

        ));
        config.setAllowedMethods(Arrays.asList(
                "GET", "POST", "PUT", "DELETE"
        ));

        config.setAllowedHeaders(Arrays.asList(
                "Authorization", "Content-Type", "X-Requested-With",
                "Accept", "Origin", "Access-Control-Request-Method",
                "Access-Control-Request-Headers", "X-XSRF-TOKEN"
        ));

        config.setExposedHeaders(Arrays.asList(
                "Access-Control-Allow-Headers", "Authorization",
                "xsrf-token", "Content-Type", "X-XSRF-TOKEN",
                "Access-Control-Allow-Origin", "Access-Control-Allow-Credentials"
        ));

        config.setAllowCredentials(true);
        config.setMaxAge(3600L);

        //UrlBasedCorsConfigurationSource 是用于配置 CORS（跨域资源共享）规则的核心类
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 将规则(config),应用到匹配的路径（"/**"：所有的路径）上。
        source.registerCorsConfiguration("/**", config);
        return source;
    }
    public void configure(HttpSecurity http) throws Exception {
        http.cors(cors -> cors.configurationSource(corsConfigurationSource()));
    }
}
